package com.example.shardingsphere.config;

import com.example.shardingsphere.config.shard.ShardingRuleConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.shardingsphere.driver.api.ShardingSphereDataSourceFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.*;

@Configuration
public class DataSourceConfig {

    private Map<String, DataSource> initRealDataSource() {
        // 配置真实数据源
        Map<String, DataSource> dataSourceMap = new HashMap<>();

        // 配置第 3 个数据源
        HikariDataSource dataSource3 = new HikariDataSource();
        dataSource3.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource3.setJdbcUrl("jdbc:mysql://10.0.0.214:3306/service_order_0");
        dataSource3.setUsername("root");
        dataSource3.setPassword("yinuo_dev");
        dataSourceMap.put("service_order_0", dataSource3);

        // 配置第 1 个数据源
        HikariDataSource dataSource1 = new HikariDataSource();
        dataSource1.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource1.setJdbcUrl("jdbc:mysql://10.0.0.214:3306/service_order_1");
        dataSource1.setUsername("root");
        dataSource1.setPassword("yinuo_dev");
        dataSourceMap.put("service_order_1", dataSource1);

        // 配置第 2 个数据源
        HikariDataSource dataSource2 = new HikariDataSource();
        dataSource2.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource2.setJdbcUrl("jdbc:mysql://10.0.0.214:3306/service_order_2");
        dataSource2.setUsername("root");
        dataSource2.setPassword("yinuo_dev");
        dataSourceMap.put("service_order_2", dataSource2);

        return dataSourceMap;
    }


    @Bean
    @Primary
    public DataSource initDataSource() throws Exception {
        // 创建 ShardingSphereDataSource
        DataSource dataSource = ShardingSphereDataSourceFactory.createDataSource(initRealDataSource(),
                // 分库分表
                Collections.singleton(ShardingRuleConfig.initShardingRuleConfiguration()), new Properties());

        // DataSourceReadWriteConfig.getDataSourceConfig() 分库分表+读写分离
        return dataSource;
    }
}
